package com.yulongtian.interviewWorks.day20221112;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

/**
 * https://leetcode.cn/problems/group-anagrams-lcci/?favorite=xb9lfcwi
 * 可
 *
 * @author yulongTian
 * @create 2022-11-12 15:58
 */
public class Test02 {
    public static void main(String[] args) {
        String[] strs = {"eat", "tea", "tan", "ate", "nat", "bat"};
        List<List<String>> lists = groupAnagrams(strs);
        System.out.println(lists.toString());
    }


    public static List<List<String>> groupAnagrams(String[] strs) {
        HashMap<String, List<String>> myMap = new HashMap<>();

        for (String str : strs) {
            StringBuilder key = new StringBuilder();
            int[] chs = new int[26];
            for (int i = 0; i < str.length(); i++) {
                chs[str.charAt(i) - 'a']++;
            }
            for (int i = 0; i < chs.length; i++) {
                if (chs[i] != 0) {
                    key.append("" + ((char) ('a' + i)) + chs[i]);
                }
            }
            //不包含
            if (!myMap.containsKey(key.toString())) {
                List<String> temp = new ArrayList<>();
                temp.add(str);
                myMap.put(key.toString(), temp);
            } else {
                //包含
                List<String> list = myMap.get(key.toString());
                list.add(str);
                myMap.put(key.toString(), list);
            }
        }
        return new ArrayList<>(myMap.values());
    }


}
